package com.controller;

import com.domain.User;
import com.mapper.UserMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.IOException;

@Controller
public class LoginController {

//    @GetMapping("/login")
//    public String login(Model model) {
//        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
//        model.addAttribute("user", "user");
//        return "login";
//    }

    @GetMapping("/login")
    public String toLoginPage() {
        return "client/login";
    }

    @Autowired
    private UserMapper userMapper;

    //登录
    @PostMapping("/toLogin")
    public String login(User user, HttpSession httpSession, Model model) throws IOException {
        User tUser = userMapper.userLogin(user);
        System.out.println("查询用户数据库结果： " + (tUser != null));
        System.out.println(tUser.toString());
        if (tUser != null) {
            //将用户对象添加到session
            httpSession.setAttribute("user", tUser);
//            request.setAttribute("user", tUser);
            model.addAttribute("user", tUser);
            //跳转到主页面
//            response.sendRedirect("/");
//            return "client/index";
            return "redirect:/";
        } else {
            model.addAttribute("msg", "账号或密码错误，请重新输入！");
            return "client/login";
//            response.sendRedirect("client/login");
        }
    }

}
